<?php

/**
 * 合同回款信息仓库
 * @author wangwx 2015-5-12
 */

namespace common\repositories\myhtsq;

use Exception;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use common\error\ErrorCode;
use common\entities\myhtsq\ContractPaymentEntity;
use common\entities\myhtsq\ContractDelPaymentModeEntity;

class ContractPaymentRepository extends BaseRepository {

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 检查是否存在合同id回款
     * @param string $contractId 合同id
     * @return boolean
     */
    public static function isExistContractPayment($contractId) {
        return ContractPaymentEntity::find()->where(['contract_id' => $contractId])->exists();
    }

    /**
     * 根据合同ID获取对应的回款信息
     * @param string $contractId 合同ID
     * @return array
     */
    public static function getPaymentInfoByContractId($contractId) {
        $query = ContractPaymentEntity::find()
                ->where(['contract_id' => $contractId])
                ->asArray()
                ->all();
        return $query;
    }
    
    /**
     * 根据合同ID获取对应的回款总额
     * @param type $contractId
     * @return type
     */
    public static function getPaymentSumByContractId($contractId) {
        return ContractPaymentEntity::find()->where(['contract_id' => $contractId])->sum('payment_amount');
    }

    /**
     * 根据回款id获取对应的回款实例
     * @param string $paymentId 回款id
     * @return ContractPaymentEntity
     */
    public static function getPaymentEntityByPaymentId($paymentId) {
        $query = ContractPaymentEntity::findOne(['payment_id' => $paymentId]);
        return $query;
    }

    /**
     * @param
     * @return
     * @author zd
     * @time 17-7-12
     */
    public static function delPaymentMode($paymentId,$delpayment=null) {

        $mode = empty($delpayment)?'yunke':'erp';
        $user = empty($delpayment)?$_SESSION['__id']:'';

        $entity = new ContractDelPaymentModeEntity();
        $entity->id = StringHelper::uuid();
        $entity->del_mode = $mode;
        $entity->del_time = date('Y-m-d H:i:s');
        $entity->user = $user;
        $entity->payment_id = $paymentId;

        //坏味道修复
        return $entity->save();

    }

    /**
     * 保存合同回款
     * @param \common\models\myhtsq\ContractPaymentModel $contractPaymentModel
     * @return boolean|string   失败|回款Guid
     */
    public static function addContractPayment($contractPaymentModel) {
        try {
            $entity = new ContractPaymentEntity();
            $entity->setAttributes($contractPaymentModel->attributes);
            if (!(isset($entity->payment_id) && !empty($entity->payment_id))) {
                $entity->payment_id = StringHelper::uuid();
            }

            $result = $entity->save();
            if ($result === FALSE) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 保存合同回款
     * @param \common\models\myhtsq\ContractPaymentModel $contractPaymentModel
     * @return boolean|string   失败|回款Guid
     */
    public static function updateContractPayment($contractPaymentModel) {
        try {
            $entity = ContractPaymentEntity::find()->where(['payment_id' => $contractPaymentModel->payment_id])->one();
            if (!isset($entity)) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_NOT_EXISTS);
            }

            $entity->setAttributes($contractPaymentModel->attributes);
            $result = $entity->update();
            if ($result === false) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->payment_id;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 根据合同id获取还没有完全关联发票的回款
     * @param string $contractId 合同id
     * @return array
     */
    public static function getContractPaymentHaveAmountByContract($contractId) {
        $sql = 'select *
                from 
                (
                        select myscrm_contract_payment.*,
                                ifnull((select sum(cur_payment_amount) from myscrm_invoice_payment where payment_id = myscrm_contract_payment.payment_id),0) as have_payment_amount
                        from myscrm_contract_payment
                ) pay where pay.payment_amount>pay.have_payment_amount and pay.contract_id = :contract_id';
        $query = ContractPaymentEntity::findBySql($sql, [':contract_id' => $contractId])
                ->asArray()
                ->all();
        return $query;
    }

    /**
     *  根据财务编号获取对应的合同回款信息
     * @param string $financeCode
     * @return array
     */
    public static function getContractPaymentInfoByFinanceCode($financeCode) {
        $query = ContractPaymentEntity::find()
                ->where(['finance_code' => $financeCode])
                ->asArray()
                ->all();
        return $query;
    }

    /**
     * 未关联发票的回款明细
     * @param array $hasInvoicePaymentIds 已经关联发票的回款
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getUnInvoicePayment($hasInvoicePaymentIds)
    {
        return ContractPaymentEntity::find()
            ->select('myscrm_contract_payment.*, myscrm_contract_manage.contract_code')
            ->leftJoin("myscrm_contract_manage", "myscrm_contract_manage.contract_id = myscrm_contract_payment.contract_id")
            ->where(['not in', 'payment_id', $hasInvoicePaymentIds])
            ->asArray()
            ->all();
    }

    /**
     * 获取回款Entity
     * @param $paymentId
     * @return ContractPaymentEntity|null
     */
    public static function getContractPaymentEntity($paymentId)
    {
        return ContractPaymentEntity::find()
            ->where(['payment_id' => $paymentId])
            ->one();
    }

}
